<template>

  <div class="mt-4 bg-light-400 bg-opacity-90">
    <div class="sm:py-8 mx-8 relative">
      <span class="h1">全部评论</span>
      <div class="divide"></div>
    </div>

    <div v-loading="replyLoading" element-loading-background="rgba(245, 245, 245,0.8)">
      <div v-if="replyList?.length !== 0" > 
        <ul
          v-infinite-scroll="load" 
          :infinite-scroll-disabled="disabled"
          infinite-scroll-distance="1"
        >
          <li class="flex justify-between sm:px-8 py-4 divide_b sm:mx-8" :key="item?._id" v-for="item in replyList?.slice(0,nextPage)">       
            <!-- 头像 -->
            <div class="mr-2">
              <RouterLink :to="`/accountCenter/postList/${item?.replier?._id}`">
                <img :src="IMG_URL_SERVER+item?.replier?.avatar?.url" :alt="item?.replier?.avatar?.name" class="avatar wh-10"/>
              </RouterLink>
            </div>
            <!-- 回复内容版块 -->
            <div class="flex-1">
              <div class="flex justify-start items-center">
                <div>
                  <RouterLink :to="`/accountCenter/postList/${item?.replier?._id}`">
                    <span class="hover:text-blue-400">{{item?.replier?.nickname}}</span>
                  </RouterLink>
                  
                </div>
                <div class="ml-2">
                  <img class="h-4" :src="IMG_URL_SERVER+item?.replier?.level?.url" alt="">
                </div>
              </div>
              <!-- 一级回复内容  -->
              <div class="md:py-6 sm:py-4 mb-py-4" v-html="item?.content"></div>

              <div class="flex justify-between h3 ">
                <div>{{dateFormat(item?.createdAt)}} <span class="text-black! font-black">{{item?.replier.perLocation}}</span></div>
                <div class="grid grid-flow-row grid-cols-3 grid-rows-1 justify-items-center items-center">
                  <div class="cursor-pointer" @click="showReply(item?._id)">回复 |</div>
                  <div class="flex items-center">
                    <template v-if="item?.isVote">
                      <div
                        :data-flag="item?.isVote"
                        @click="addLikingReply(item?._id,$event)"
                        class="mr-1 cursor-pointer bg-sky-500 i-carbon-thumbs-up-filled">
                      </div>
                      <div ref="count" :data-count="item?._id">{{item?.voteCount}}</div>
                    </template>
                    <template v-else>
                      <div 
                        :data-flag="item?.isVote"
                        @click="addLikingReply(item?._id,$event)" 
                        class="mr-1 cursor-pointer i-carbon-thumbs-up">
                      </div>
                      <div ref="count" :data-count="item?._id">{{item?.voteCount}}</div>
                    </template>
                    

                  </div>
                  <div class="i-carbon-thumbs-down"></div>
                </div>
              </div>
              

              <!-- 灰色回复框 -->
              <div v-if="item?.childrenComments?.length > 0 || keyId === item?._id" class="my-4 sm:px-12 py-4 w-full bg-gray-200 ">
                <SimpleEditor v-if="keyId === item?._id" :rootCommentId="item?._id" :handleReload="handleReload" :picList="picList" :stopEmitImg="true" :stopPasteImg="true"></SimpleEditor>

                <ul >
                  <!-- 二级回复内容 -->
                  <li :key="rp?._id" v-for="rp in item?.childrenComments">
                    <div class="flex justify-start items-center">
                      <div class="wh-6 mr-2">
                        <RouterLink :to="`/accountCenter/postList/${rp?.replier._id}`">
                          <img class="avatar" :src="IMG_URL_SERVER+rp?.replier?.avatar?.url" :alt="rp?.replier?.avatar?.name">
                        </RouterLink>
                      </div>
                    
                      <RouterLink :to="`/accountCenter/postList/${rp?.replier._id}`">
                        <div class="text-blue-500 hover:text-blue-400">{{rp?.replier?.nickname}}</div>
                      </RouterLink>
                      <div class="ml-2">
                        <img class="h-4" :src="IMG_URL_SERVER+item?.replier?.level?.url" alt="">
                      </div>
                      <div class="ml-2" v-if="rp?.tier">
                        <span class="mr-2">回复</span>
                        <RouterLink :to="`/accountCenter/postList/${rp?.replyTo?._id}`">
                          <span class="text-blue-500 hover:text-blue-400">{{rp?.replyTo?.nickname}}</span>
                        </RouterLink>
                      </div>
                    </div>
                    <div class="pl-8" v-html="rp?.content"></div>

                    <div class="flex justify-end h3">
                      <div class=" grid grid-flow-row grid-cols-3  grid-rows-1 justify-items-center items-center  ">
                        <div class="cursor-pointer" @click="showReply(rp?._id)">回复 |</div>
                        <div class="flex items-center">
                          <template v-if="rp?.isVote">
                            <div
                              :data-flag="rp?.isVote"
                              @click="addLikingDiscuss(rp?._id,$event)"
                              class="mr-1 cursor-pointer bg-sky-500 i-carbon-thumbs-up-filled">
                            </div>
                            <div ref="count" :data-count="rp?._id">{{rp?.voteCount}}</div>
                          </template>
                          <template v-else>
                            <div 
                              :data-flag="rp?.isVote"
                              @click="addLikingDiscuss(rp?._id,$event)" 
                              class="mr-1 cursor-pointer i-carbon-thumbs-up">
                            </div>
                            <div ref="count" :data-count="rp?._id">{{rp?.voteCount}}</div>
                          </template>
                        </div>
                        
                        <div class="i-carbon-thumbs-down"></div>
                      </div>
                    </div>
                    <SimpleEditor v-if="keyId === rp?._id" :rootCommentId="rp?._id" :handleReload="handleReload" :picList="picList" :stopEmitImg="true" :stopPasteImg="true" :rpId="rp?._id"></SimpleEditor>

                  </li>
                </ul>
              </div>
            </div> 

          </li>
        </ul>
        <div v-if="loading" class=" bg-light-400 h-20 flex justify-center items-center">
          <div class="animate-spin mr-1 bg-blue-500 wh-8! i-carbon-restart "></div>
          <span class="text-2xl leading-20">
            加载中...
          </span>
        </div >
        <div v-if="noMore" class=" bg-light-400 h-20 text-center">
          <span class="text-2xl leading-20 ">
            没有更多数据了
          </span>
        </div >
      </div>
      <template v-else>
        <el-empty description="暂时还没有评论哦" />
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import {fetchAddLikingReply,fetchDelLikingReply,fetchReplyList,fetchAddLikingDiscuss,fetchDelLikingDiscuss} from "@/server";
import { IMG_URL_SERVER } from "@/config";
import { dateFormat } from "@/utils"


defineProps<{
  picList:any
}>()


//reload 重载
const { reloadFlag,handleReload } = inject<any>('reload')
//authStore登录用户数据
const authStore = useAuthStore()
//route 
const route = useRoute()
//utilsStore
const utilsStore = useUtilsStore()
//评论列表
const replyList:any = ref([])
//等待加载回复
const replyLoading = ref(true)


//点赞计数
const count = ref()
//点击点赞一级评论
const addLikingReply = (id:any,e:any)=>{
  //保护条款
  if(!authStore.isAuthenticated){
    utilsStore.dialogTableVisible = true 
    return false;
  }

  let dom = count.value.find(function(val:any){
    return val.dataset.count === id; //条件，返回真假
  })
  
  if(e.target.dataset?.flag === 'false'){   
    fetchAddLikingReply(id,()=>{
      e.target.dataset.flag = 'true'
      dom.textContent = Number(dom.textContent)+1
      e.target.classList.add("i-carbon-thumbs-up-filled","bg-sky-500")
      e.target.classList.remove("i-carbon-thumbs-up")  
      return true
    })
  }else{
    fetchDelLikingReply(id,()=>{
      e.target.dataset.flag = 'false'
      dom.textContent = Number(dom.textContent)-1
      e.target.classList.remove("i-carbon-thumbs-up-filled","bg-sky-500")
      e.target.classList.add("i-carbon-thumbs-up")
      return true

    })
  } 
}
//点击点赞二三级评论
const addLikingDiscuss = (id:any,e:any)=>{
  //保护条款
  if(!authStore.isAuthenticated){
    utilsStore.dialogTableVisible = true 
    return false;
  }

  let dom = count.value.find(function(val:any){
    return val.dataset.count === id; //条件，返回真假
  })
  
  if(e.target.dataset?.flag === 'false'){   
    fetchAddLikingDiscuss(id,()=>{
      e.target.dataset.flag = 'true'
      dom.textContent = Number(dom.textContent)+1
      e.target.classList.add("i-carbon-thumbs-up-filled","bg-sky-500")
      e.target.classList.remove("i-carbon-thumbs-up")  
      return true
    })
  }else{
    fetchDelLikingDiscuss(id,()=>{
      e.target.dataset.flag = 'false'
      dom.textContent = Number(dom.textContent)-1
      e.target.classList.remove("i-carbon-thumbs-up-filled","bg-sky-500")
      e.target.classList.add("i-carbon-thumbs-up")
      return true
    })
  } 
}

//显示回复框
const keyId = ref('')
const showReply = (id:string)=>{
  //保护条款
  if(!authStore.isAuthenticated){
    utilsStore.dialogTableVisible = true 
    return false;
  }
  keyId.value = id
}


//加载更多
let PageStep:number = 5 //跳过
let nextPage = ref(PageStep)
const loading = ref(false)
const noMore = computed(() => nextPage.value >= (replyList.value?.length-1))
const disabled = computed(() => loading.value || noMore.value )

const load = () => {
  loading.value = true
  setTimeout(() => {
    nextPage.value += PageStep 
    loading.value = false
  }, 500)
}

//更新时发送fetch
watchEffect(()=>{
  if(route.params.id && reloadFlag.value){
    //获取回复列表
    fetchReplyList(route.params.id as string, ()=>true).then((data)=>{  
      replyList.value =  data
      setTimeout(() => {
        replyLoading.value = false
      }, 300)
    })
  }
},{flush:'post'})

</script>

<style scoped lang="scss">
.mb-py-4{
  @media screen and (max-width:640px) {
    padding-top: 1rem;
    padding-bottom: 1rem;
  }
}
</style>